package com.qian.api.ddj.util;

import com.yaowk.api.common.BaseException;

import java.io.UnsupportedEncodingException;
import java.security.*;

public class RSASignUtil {

    public static String sign(String content ,PrivateKey privateKey){

        try{

            Signature signature = Signature.getInstance("SHA1WithRSA");
            signature.initSign(privateKey);
            signature.update(content.getBytes("UTF-8"));
            byte[] signd = signature.sign();
            return Base64.encode(signd);
        }catch (Exception e){
            e.printStackTrace();
            throw  new BaseException("出错！");
        }
    }

    public static boolean checkKey(String content, String sign, PublicKey publicKey){
        Signature signature = null;
        try {
            signature = Signature.getInstance("SHA1WithRSA");
            signature.initVerify(publicKey);
            signature.update(content.getBytes("UTF-8"));

            return signature.verify(Base64.decode(sign));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;

    }
}
